package gui;

import java.awt.Component;
import java.awt.FlowLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;

import model.Stack;
import service.Service;

public class EditStack extends JFrame {
    private final Controller controller = new Controller();
    private JTextField txtTrays;
    private JButton btnEdit, btnCancel;
    private Stack stack;
    private Component owner;

    public EditStack(Stack stack) {
	this.stack = stack;
	this.setSize(300, 120);

	setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
	setVisible(true);
	setTitle("Edit Stack");
	getContentPane().setLayout(new GridLayout(3, 0, 0, 0));

	JPanel panel = new JPanel();
	FlowLayout flowLayout = (FlowLayout) panel.getLayout();
	flowLayout.setAlignment(FlowLayout.LEFT);
	getContentPane().add(panel);

	JLabel lblTrays = new JLabel("Trays:");
	panel.add(lblTrays);

	txtTrays = new JTextField();
	panel.add(txtTrays);
	txtTrays.setColumns(10);
	txtTrays.setText(this.stack.getNumberOfTrays() + "");

	JPanel panel_2 = new JPanel();
	FlowLayout flowLayout_2 = (FlowLayout) panel_2.getLayout();
	flowLayout_2.setAlignment(FlowLayout.RIGHT);
	getContentPane().add(panel_2);

	btnEdit = new JButton("Edit");
	panel_2.add(btnEdit);
	btnEdit.addActionListener(controller);

	btnCancel = new JButton("Cancel");
	panel_2.add(btnCancel);
	btnCancel.addActionListener(controller);
    }

    public EditStack(Component owner, Stack stack) {
	this(stack);
	this.owner = owner;
    }

    private class Controller implements ActionListener {
	@Override
	public void actionPerformed(ActionEvent e) {
	    if (e.getSource() == btnCancel) {
		EditStack.this.dispose();
	    } else if (e.getSource() == btnEdit) {
		try {
		    int trays = Integer.parseInt(txtTrays.getText());

		    Stack s = Service.getInstance().editStack(stack, trays);

		    if (s != null) {
			if (owner instanceof StackInfoDialog)
			    ((StackInfoDialog) owner).updateStackInfo();

			EditStack.this.dispose();
		    } else {
			JOptionPane.showMessageDialog(EditStack.this,
				"Stack could not be edited", "Error",
				JOptionPane.ERROR_MESSAGE);
		    }
		} catch (NumberFormatException ex) {
		    JOptionPane.showMessageDialog(EditStack.this,
			    "Trays should be number", "Error",
			    JOptionPane.ERROR_MESSAGE);
		}
	    }

	}

    }
}